﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace _4_使用Dispatcher
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ModifyUI()
        {
            Thread.Sleep(TimeSpan.FromSeconds(5));

            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate () {
                lalHello.Content = "欢迎你光临WPF的世界,Dispatche  同步方法 ！！";
            });
        }

        private void btnThd_Click(object sender, RoutedEventArgs e)
        {
            ModifyUI();//这里为同步调用，将会产生阻塞，窗体会卡顿
        }

        public void ModifyUIPublic(string msg)
        {
            //这个为异步调用，为非阻塞，窗体不会卡顿
            new Thread(() => {
                Thread.Sleep(TimeSpan.FromSeconds(5));
                Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => {
                    //下面为控件的属性更改代码
                    this.lalHello.Content = msg + DateTime.Now.ToString();

                }));
            }
            ).Start();
        }

        private void btnAppBeginInvoke_Click(object sender, RoutedEventArgs e)
        {
            //这个为异步调用，为非阻塞，窗体不会卡顿
            new Thread(() => {
                Thread.Sleep(TimeSpan.FromSeconds(5));
                Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => {
                    //下面为控件的属性更改代码
                    this.lalHello.Content = "欢迎你光临WPF的世界,Dispatche 异步方法！！"+ DateTime.Now.ToString();

                }));
            }
            ).Start();
        }
    }
}
